const mixin = require('../../mixins');
Component({
	behaviors: [mixin],
	data: {
		playStatus: false, // 当前播放状态
		status: false,
		trackingParams: null
	},
	properties: {
		mf_data: Object,
		customAppear: Boolean,
		isSp: Boolean,
		// stspEvent: Function,
	},
	lifetimes: {
		attached() {

		},
		ready() {
			try {
				this.videoContext = wx.createVideoContext(this.properties.mf_data.id, this);
				if (this.properties.mf_data.trackingParams) this.data.trackingParams = this.properties.mf_data
					.trackingParams
			} catch (e) {}
		}
	},
	"observers": {
		"customAppear": function(newVal, oldVal) {
			const {
				mf_data
			} = this.properties;
			if (mf_data.autoPlay || this.data.status) {
				if (newVal) {
					// 替换成你的 video 组件的 id
					this.onAppear()
				} else {
					if (this.data.playStatus) {
						this.onDisappear()
					}else{
						if(mf_data.autoPlay){
							this.onAppear()
						}
					}
				}
			}
		}
	},
	detached() {},
	methods: {
		bindplay() {
			if (this.videoContext) {
				this.setData({
					playStatus: true
				});
			}
		},
		bindpause() {
			if (this.videoContext) {
				this.setData({
					playStatus: false
				});
			}
		},
		bindPlayVideo() {
			if (this.videoContext) {
				this.videoContext.play()
			}
		},
		play() {
			const {
				isSp
			} = this.properties;
			if (!this.videoContext) {
				this.videoContext = wx.createVideoContext(this.properties.mf_data.id, this);
			}


			if (this.videoContext && !this.data.playStatus) {
				this.videoContext.play();
				this.setData({
					playStatus: true,
					status: true
				})
				if(isSp) {
					this.triggerEvent('stspEvent', false);
				}
			}

			// 播放视频 埋点参数
			if (this.data.trackingParams) {
				this.triggerEvent('triggerComponent', {
					data: {
						trackData: this.data.trackingParams,
						type: "track"
					}
				}, {
					bubbles: true,
					composed: true
				});
			}
		},
		pause() {
			if (this.videoContext) {
				this.videoContext.pause();
				this.setData({
					playStatus: false
				})
			}
		},
		stop() {
			if (this.videoContext && this.data.playStatus) {
				this.videoContext.stop();
				this.setData({
					playStatus: false
				})
			}
		},
		onDisappear() {
			this.stop()
		},
		onEnded() {
			const {
				mf_data,isSp
			} = this.properties;
			if(isSp) {
				this.triggerEvent('stspEvent', true);
			}
			if (mf_data.loop && !isSp) {
				this.videoContext.seek(0);
				this.videoContext.play();
			}
			
		},
		onAppear() {
			const {
				mf_data,
				customAppear,
				isSp
			} = this.properties;
			// this.play();
			if (isSp) {
				if ((mf_data.autoPlay || this.data.status) && this.properties.customAppear) {
					this.play();
				}
			} else {
				if (mf_data.autoPlay || this.data.status) {
					this.play();
				}
			}
		},
	},
});